import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
import { AppModule } from './app.module';
import { ResponseInterceptor } from './common/interceptors/response.interceptor';
import { HttpExceptionFilter } from './common/filters/http-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );

  // 设置全局路由前缀
  app.setGlobalPrefix('api');

  // 全局响应拦截器
  app.useGlobalInterceptors(new ResponseInterceptor());

  // 全局异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter());

  // CORS配置
  app.enableCors();

  // Swagger文档配置
  const config = new DocumentBuilder()
    .setTitle('短剧后端API')
    .setDescription('短剧平台后端服务API文档')
    .setVersion('1.0')
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api-docs', app, document);

  // 添加Swagger JSON端点
  app.use('/api-docs-json', (req, res) => {
    res.setHeader('Content-Type', 'application/json');
    res.send(document);
  });

  const port = process.env.PORT || 3001;
  const environment = process.env.NODE_ENV;

  await app.listen(port);
  console.log(`🚀 应用已启动`);
  console.log(`📍 环境: ${environment}`);
  console.log(`🌐 端口: ${port}`);
  console.log(`📚 API基础地址: http://localhost:${port}/api`);
  console.log(`📖 Swagger文档地址: http://localhost:${port}/api-docs`);
  console.log(`🔗 Swagger JSON地址: http://localhost:${port}/api-docs-json`);

  if (environment === 'development') {
    console.log(`🔧 开发模式已启用`);
  } else if (environment === 'production') {
    console.log(`🚀 生产模式已启用`);
  }
}
bootstrap();
